import {Component, ViewChild} from '@angular/core';
import {
  NavController,
  NavParams,
  ViewController,
  Content,
  TextInput,
  Events,
  ModalController,
  IonicPage,
  Navbar, ToolbarTitle, Platform
} from 'ionic-angular';
import {AppConfig} from '../../app/app.config';
import {
  Storage
} from '@ionic/storage'
import {GetGroupUsersPage} from '../get-group-users/get-group-users'
import {Dexie} from 'dexie'
import {listener} from "@angular/core/src/render3/instructions";
import {Md5} from "ts-md5";
import {Http, Headers, RequestOptions, URLSearchParams} from "@angular/http";
import { baseCommon } from '../../common/baseCommon';
/**
 * Generated class for the ChatDetailPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-chat-detail',
  templateUrl: 'chat-detail.html',
})
export class ChatDetailPage {

  isOpenEmojiPicker = false;
  editorMessage: string = '';
  groupID: any;
  groupName: any;
  currentUser: any;
  rel: any = [];
  imageURL: any = '';
  username: any;
  listener: any;
  time: any;
  groupUser:any = [];
  userPhone:any = [];
  sessionID:any;
  @ViewChild(Content) content: Content;
  @ViewChild('chatInput') messageInput: TextInput;

  constructor(public navCtrl: NavController,
              public http: Http,
              public navParams: NavParams,
              public viewCtrl: ViewController,
              public storage: Storage,
              public modalCtrl: ModalController,
              public event: Events,
              public platform: Platform) {
    this.groupID = navParams.get('groupID');
    this.groupName = navParams.get('groupName');
  }

  ionViewDidEnter() {
    console.log(AppConfig.socket);
    this.storage.get('sessionID').then(val=>{
      baseCommon.getGroupAllUser(this.http , this.groupID , val)
      .then(val=>{
        this.groupUser = val;
        this.storage.get('phone').then(val => {
          this.currentUser = val;
          this.query(this.groupID, function (val) {
            AppConfig.result = val;
          });
    
          setTimeout(() => {
            this.rel = AppConfig.result;
            this.rel.forEach(rels=>{
              this.groupUser.forEach(user=>{
                if(user.phone == rels.sender){
                  rels.imageURL = user.imageURL;
                  rels.username = user.nickname;
                }
              })
            });
          }, 100);
          if (this.scrollToBottom2 != null) {
            this.scrollToBottom2();
          }
        })
      });
    })

    AppConfig.viewCtrl = this.viewCtrl;
    AppConfig.currentPage = this.groupID;
    this.storage.get('userImg').then(val => {
      this.imageURL = val;
    })

    this.storage.get('nickname').then(val => {
      this.username = val;
    });

    //听取消息的订阅
    this.event.subscribe('chat.received', (mes, time) => {
      this.storage.get('nickname').then(val => {
        var value = {//此对象只是一个示例，indexedDB可以保存任何形式的对象
          'groupID': mes.groupID,
          'phone':mes.phone,
          'message': mes.message,
          'date': this.timestampToTime(mes.date),
          'username': mes.username,
          'imageURL':'',
          'sender':mes.sender
        };
        this.insert(value);
        this.groupUser.forEach(user=>{
          if(user.phone = mes.sender){
            value.imageURL = user.imageURL;
            return;
          }
        })
        if (mes.username == val) {
          return;
        } else {
          this.rel.push(value);
          this.listen();
        }
      })
    })
  }

  /**
   * 发送成功查询
   */
  listen() {
    setTimeout(() => {
      if (this.scrollToBottom != null) {
        this.scrollToBottom();
      } else {
        this.listen()
      }
    }, 200);
  }

  /**
   * 获取圈子用户
   *
   * @memberof ChatDetailPage
   */
  getGroupUser() {
    let model = this.modalCtrl.create(GetGroupUsersPage, {'groupName': this.groupName, 'groupID': this.groupID});
    model.dismiss(data => {
      AppConfig.viewCtrl = this.viewCtrl
    })
    model.present();
  }


  /**
   * dismiss
   *
   * @memberof ChatDetailPage
   */
  dismiss() {
    this.viewCtrl.dismiss(this.groupID);
  }

  /**
   * 切换表情组件
   *
   * @memberof ChatDetailPage
   */
  switchEmojiPicker() {
    this.isOpenEmojiPicker = !this.isOpenEmojiPicker;
    this.scrollToBottom();
  }

  /**
   * 发送信息
   *
   * @returns
   * @memberof ChatDetailPage
   */
  sendMessage() {
    this.isOpenEmojiPicker = false;
    if (!this.editorMessage.trim())
      return;
    
    /**
     * 先展示出来
     */
    this.time = this.timestampToTime(Date.now());
    let sendMes = {
      imageURL: this.imageURL,
      date: this.time,
      username: this.username,
      message: this.editorMessage,
      status: 'pending'
    }
    this.rel.push(sendMes);
    setTimeout(() => {
      this.scrollToBottom();
      this.editorMessage = '';
    }, 100);

    /*
    * 请求服务器，成功就存入数据库
    */
    var jsonObject = {
      groupID: this.groupID,
      message: this.editorMessage,
      messageNum: Math.round(Math.random() * 100000000),
    };
    AppConfig.socket.emit('message', jsonObject)
  }

  /**
   * 输入框获得焦点
   *
   * @memberof ChatDetailPage
   */
  focus() {
    this.isOpenEmojiPicker = false;
    this.content.resize();
  }


  /**
   * 滚动条滚动到最下面
   *
   * @returns {*}
   * @memberof ChatDetailPage
   */
  scrollToBottom(): any {
    setTimeout(() => {
      if (this.content != null && this.content.scrollToBottom != null) {
        try {
          this.content.scrollToBottom();
        } catch (e) {
          console.log(e)
        }
      }
    }, 200)
  }

  scrollToBottom2(): any {
    setTimeout(() => {
      if (this.content != null && this.content.scrollToBottom != null) {
        try {
          this.content.scrollToBottom(0);
        } catch (e) {
          console.log(e)
        }
      }
    }, 200)
  }


  /**
   * 插入数据
   *
   * @param {any} value
   * @memberof ChatDetailPage
   */
  insert(value) {
    var time = this.time;
    var rel = this.rel;
    AppConfig.db.message.add(value).then(function () {
      setTimeout(rel.forEach(el => {
        if (el.date == time) {
          el.status = 'ended';
        }
      }), 3000);
    })
  }

  /**
   *
   * 查询数据
   * @param groupID
   * @param success
   */
  query(groupID, success) {
    AppConfig.db.message.where({groupID: groupID}).toArray().then(function (value) {
      success(value)
    });
  }

  /**
   * 将时间戳转化为为时间格式
   *
   * @param {any} timestamp
   * @returns
   * @memberof ChatDetailPage
   */
  timestampToTime(timestamp) {
    var time = new Date(timestamp);
    var year = time.getFullYear();
    var month = time.getMonth() + 1;
    var date = time.getDate();
    var hours = time.getHours();
    var minutes = time.getMinutes();
    var seconds = time.getSeconds();
    return year + '-' + this.add0(month) + '-' + this.add0(date) + ' ' + this.add0(hours) + ':' + this.add0(minutes) + ':' + this.add0(seconds);
  }

  add0(m) {
    return m < 10 ? '0' + m : m
  }

  
}
